package com.huika.dealontop.control.login.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.huika.dealontop.R;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.login.event.LoginEvent;
import com.huika.dealontop.utils.LoginUtils;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.dealontop.views.cleardit.ClearableEditText;

import org.json.JSONObject;

import java.util.Arrays;

import de.greenrobot.event.EventBus;


/**
 * @author CaiLu
 * @ClassName: LoginActivity
 * @date 2015年12月08日
 */
public class LoginActivity extends BaseAct {
    private ClearableEditText etPhone;
    private ClearableEditText etPsw;
    private Button btnLogin;
    private TextView btnRegister;
    private TextView btnFind;
    LoginButton loginButton;
    CallbackManager callbackManager;
    private String phone;
    private LoginUtils mLoginUtils;
    private AccessTokenTracker accessTokenTracker;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_login);
        //初始化EventBus
        EventBus.getDefault().register(this);

        //一进入就创建一个登入类,
        mLoginUtils = new LoginUtils(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this, UIUtils.getString(R.string.facebook_app_id));
    }

    @Override
    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }

    @Override
    protected void initWidget() {
        initFacebookLogin();
        //标题混杂设置代码
        TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1, -1, -1);
        titleBarHelper.setLeftMsg("");
        RelativeLayout rL = (RelativeLayout) findViewById(R.id.rl_title);
        TextView leftArrowImage = (TextView) findViewById(R.id.left);
        Drawable leftDrawable = UIUtils.getResources().getDrawable(R.mipmap.register_white_arrow);
        leftDrawable.setBounds(0, 0, UIUtils.dip2px(19), UIUtils.dip2px(20));
        leftArrowImage.setCompoundDrawables(leftDrawable, null, null, null);
        View titleline = (View) findViewById(R.id.title_line);
        titleline.setVisibility(View.GONE);
        rL.setBackgroundColor(Color.TRANSPARENT);


        etPhone = (ClearableEditText) findViewById(R.id.et_phone_al);
        etPsw = (ClearableEditText) findViewById(R.id.et_psw_al);
        btnLogin = (Button) findViewById(R.id.btn_login_al);
        btnRegister = (TextView) findViewById(R.id.btn_register_al);
        btnFind = (TextView) findViewById(R.id.btn_findpsw_al);

        etPsw.addTextChangedListener(new MyPassWordWatcher(etPsw));

        // editTextValidator = new EditTextValidator(this).add(new
        // ValidationModel(etPsw, new PassWordValidation())).execute();
        initListener();
        initEdit();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }

    String userId = "";

    private void initFacebookLogin() {
        FacebookSdk.sdkInitialize(this.getApplicationContext());

        loginButton = (LoginButton) findViewById(R.id.login_facebook_button);
        //  loginButton.setReadPermissions("user_friends","public_profile");

        //下面这段是为了将背景图片设置到facebook的图片背景上面
        loginButton.setTextColor(Color.TRANSPARENT);
        loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        Drawable myImage = UIUtils.getResources().getDrawable(R.mipmap.register_facebook);
        myImage.setBounds(0, 0, UIUtils.dip2px(46), UIUtils.dip2px(46));
        loginButton.setCompoundDrawables(null, myImage, null, null);




        //添加facebook的权限
       // LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_friends", "email", "user_about_me"));
        //loginButton.setReadPermissions(Arrays.asList("email", "user_photos", "public_profile"));

       // loginButton.setReadPermissions("email");
        //LoginManager.getInstance().logInWithReadPermissions(this,Arrays.asList("email"));
        loginButton.setReadPermissions(Arrays.asList("email","public_profile"));
        callbackManager = CallbackManager.Factory.create();
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(final LoginResult loginResult) {
                // App code

                GraphRequest  request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject me, GraphResponse response) {
                                if (response.getError() != null) {
                                } else {
                                    String email = me.optString("email");
                                    mLoginUtils.setEmail(email);
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "email");
                request.setParameters(parameters);
                request.executeAsync();

            }

            @Override
            public void onCancel() {
                // App code
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
            }
        });


        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(
                    AccessToken oldAccessToken,
                    AccessToken currentAccessToken) {
                // Set the access token using
                // currentAccessToken when it's loaded or set.

                userId = currentAccessToken.getUserId();

                Log.e("id.", userId);
                Log.e("id.2", currentAccessToken.getApplicationId());
            }
        };
        // If the access token is available already assign it.
        AccessToken accessToken = AccessToken.getCurrentAccessToken();

        ProfileTracker profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(
                    Profile oldProfile,
                    Profile currentProfile) {
                String USER_ID_KEY = currentProfile.getId();
                String nickName = currentProfile.getName();


                mLoginUtils.setIsThirdToken("1");
                mLoginUtils.setIsThirdType("1");
                mLoginUtils.setNickName(nickName);
                mLoginUtils.thirdLogin(userId);


            }
        };

    }

    private void initListener() {

        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        btnFind.setOnClickListener(this);
    }

    class MyPassWordWatcher implements TextWatcher {
        private EditText editText;
        private String tempStr;

        public MyPassWordWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void afterTextChanged(Editable s) {
            //文本框将打不出空格内容.
            if (tempStr.indexOf(" ") != -1) {
                editText.setText(tempStr.trim());
                editText.setSelection(tempStr.length());
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //文本框的内容如果是空格的话,会将内容重新设置为空字符串.
            if (s.toString().equals(" ")) {
                editText.setText("");
            } else {
                tempStr = s.toString();
            }
        }

    }

    /**
     * @说明:初始化账号
     * @author: zwy
     */
    private void initEdit() {
        String userName = PreferencesHelper.getString(PreferencesHelper.KEY_LOGIN_NAME);
        if (userName != null && !TextUtils.isEmpty(userName)) {
            etPhone.setText(userName);
        }
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login_al:
                login();
                break;
            case R.id.btn_register_al:
                //showActivity(this,SuccessPageTwo.class);
                showActivity(LoginActivity.this, RegisterActivity.class);
                break;
            case R.id.btn_findpsw_al:
                //showActivity(LoginActivity.this, RegisterActivity.class);
                showActivity(LoginActivity.this, FindPwdActivity.class);
                break;
            default:
                break;
        }
    }

    private void login() {
        phone = getInputStr(etPhone);
        if (phone == null || TextUtils.isEmpty(phone)) {
            showToastMsg(getString(R.string.register_login_phone));
            return;
        }
        String pwd = getInputStr(etPsw);
        if (pwd == null || TextUtils.isEmpty(pwd)) {
            showToastMsg(getString(R.string.register_login_password));
            return;
        }
        showLoadingDialog("");
        mLoginUtils.login(phone, pwd);
    }

    public void onEventMainThread(LoginEvent loginEvent) {
        dismissLoadingDialog();
        if (loginEvent.getLoginStatus() == 1) {
            this.finish();
        } else {
            showToastMsg(loginEvent.getMsg());
        }
    }

    @Override
    protected void onDestroy() {
        accessTokenTracker.stopTracking();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
